package com.example.weatherapi.service.impl;

import com.example.citycommon.dto.WeatherResponse;
import com.example.weatherapi.client.CacheServiceClient;
import com.example.weatherapi.service.WeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class WeatherServiceImpl implements WeatherService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CacheServiceClient cacheServiceClient;

    @Override
    public WeatherResponse searchWeather(String cityid) {
        // 首先尝试从缓存中获取数据
        WeatherResponse cachedResponse = cacheServiceClient.getWeatherFromCache(cityid);
        if (cachedResponse != null) {
            return cachedResponse;
        }

        // 如果缓存中没有，则调用第三方 API
        String url = "https://apis.tianapi.com/tianqi/index?key=e90f6ad1e7a914d9f1aa97ccba8bfa9f&type=7&city=" + cityid;
        WeatherResponse response = restTemplate.getForObject(url, WeatherResponse.class);

        // 将新获取的数据存入缓存
        if (response != null) {
            cacheServiceClient.saveWeatherToCache(cityid, response);
        }

        return response;
    }
}